package com.yunbiao.ybbusstopplate.utils;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BitmapRecycle {
    private List<Bitmap> bitmaps;

    public BitmapRecycle(){
        bitmaps=new ArrayList<>();
    }

    public synchronized void recycleBitmaps(){
        Iterator<Bitmap> iterator = bitmaps.iterator();
//        Log.d("imageloadutils", "size: "+bitmaps.size());
        while (iterator.hasNext()){
            Bitmap bitmap = iterator.next();
            iterator.remove();
            if (bitmap!=null&&!bitmap.isRecycled()){
                bitmap.recycle();
                bitmap=null;
//                Log.d("imageloadutils","recycleBitmaps--> size:"+bitmaps.size());
            }
        }
//        System.gc();
    }

    public void addBitmap(ImageView imageView, View backView){
        if (imageView!=null){
            Drawable img_drawable = imageView.getDrawable();
            if (img_drawable!=null){
                Bitmap bmp=null;
                if (img_drawable instanceof BitmapDrawable){
                    BitmapDrawable drawable =(BitmapDrawable)img_drawable;
                    bmp = drawable.getBitmap();
                }if (null != bmp && !bmp.isRecycled()){
                    bitmaps.add(bmp);
                }
            }
        }

        if (backView!=null){
            Drawable bg_drawable = backView.getBackground();
            if (bg_drawable!=null&&bg_drawable instanceof BitmapDrawable){
                BitmapDrawable background = (BitmapDrawable) bg_drawable;
                Bitmap bitmap = background.getBitmap();
                if (null != bitmap && !bitmap.isRecycled()){
                    bitmaps.add(bitmap);
                }
            }
        }

    }
}
